package chpt12;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.junit.jupiter.api.Test;

public class BatchInsertTest {
	String url = "jdbc:mysql://localhost:3306/demodb?serverTimezone=Asia/Chongqing";
	String userName = "root";
	String password = "root123";
	
	

	@Test
	public void statmentBatchTest() {
		int num = 10000; // 插入记录数
		String strSql = "insert into students values(null,?,?,?,null)";
		try (Connection con = DriverManager.getConnection(url, userName, password);
				PreparedStatement pstmt = con.prepareStatement(strSql)) {
			con.setAutoCommit(false); // sql语句不会立即执行，需执行commit()时才会执行
			Random rnd = new Random();
			for (int i = 0; i < num; i++) {
				pstmt.setString(1, "sno-" + i);
				pstmt.setString(2, "name-" + i);
				double gpa = rnd.nextDouble() * 4;
				pstmt.setDouble(3, gpa);
				pstmt.addBatch(); // 将参数添加到此PreparedStatement对象的批处理命令中
			}
			
			int[] executeBatch = pstmt.executeBatch();// 返回每条SQL语句影响的行数
			con.commit(); // 提交事务，这时才真正执行相关SQL语句
			for (int i = 0; i < 3; i++) { // 只输出前3条语句的执行结果
				System.out.print(executeBatch[i] + " ");
			}
			System.out.println("END");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}